package com.press.controllers.admin;

import com.alibaba.fastjson.JSONObject;
import com.press.bean.ContentBean;
import com.press.bean.MappingBean;
import com.press.bean.TaxonomyBean;
import com.press.bean.UserBean;
import com.press.services.ContentService;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by liao on 2016/10/6.
 */
@Controller
@RequestMapping("/ArticleController")
public class ArticleController {
    @Resource(name="contentService")
    private ContentService contentService ;
    private static Logger log = Logger.getLogger(ArticleController.class);
    public ContentService getContentService() {
        return contentService;
    }

    public void setContentService(ContentService contentService) {
        this.contentService = contentService;
    }

    @RequestMapping("/addArticle")
    public void addArticle(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Map map  = new HashMap<>();
        JSONObject json = new JSONObject();
        String title = request.getParameter("title");
        String tip = request.getParameter("tip");
        map.put("content_title",title);
        map.put("content_text",request.getParameter("content"));
        String[] arr = request.getParameter("classfyArr").split("/");
//        System.out.println("数组长度"+arr.length);
        map.put("arr",arr);
        map.put("content_thumbnail",request.getParameter("picPath"));
        map.put("content_summary",request.getParameter("summary"));
        map.put("content_remarks",request.getParameter("remarks"));
        map.put("user_id",((UserBean)request.getSession().getAttribute("admin")).getUser_id());
        map.put("content_author",((UserBean)request.getSession().getAttribute("admin")).getUser_nickname());
//        System.out.println("requestArr"+request.getParameter("classfyArr"));
//        System.out.println("title"+map.get("content_title"));
//        System.out.println("ControllerArr"+map.get("arr"));
        boolean result =false;
        if("add".equals(tip)){
            map.put("tip","add");
            result = contentService.addContent(map);
        }else if("edit".equals(tip)){
            String content_id = request.getParameter("content_id");
            String remark = request.getParameter("remark");
            map.put("remark",remark);
            map.put("content_id",content_id);
            boolean deleteMapping = contentService.deleteMapping(content_id);
            if(deleteMapping){
                result = contentService.updateContent(map);
                System.out.println("update"+result);
            }
        }else if("draft".equals(tip)){
            map.put("tip","draft");
            result = contentService.addContent(map);
        }

        if(result){
            json.put("msg","yes");
        }else{
            json.put("msg","no");
        }
        response.getWriter().print(json.toJSONString());
    }
    @RequestMapping("/getArticle")
    public void getArticle(HttpServletRequest request, HttpServletResponse response) throws IOException {
        JSONObject json = new JSONObject();
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        //System.out.println("re"+request.getParameter("data"));
        List<ContentBean> contentList =  contentService.getContent();
        List<ContentBean> contentBinList = contentService.getBinContent();
        List<MappingBean> mappingBeenList = contentService.getmapping();
        List<ContentBean> contentDraftList = contentService.getDraftContent();
        //System.out.println("MappingBeanList.isEmpty()"+MappingBeanList.isEmpty()+MappingBeanList.size());
        String binCount = contentService.getBinCount();
        String noBinCount = contentService.getNoBinCount();
        String draftCount = contentService.getDraftCount();
        json.put("contentList",contentList);//所以文章
        json.put("binCount",binCount);
        json.put("noBinCount",noBinCount);
        json.put("contentBinList",contentBinList);//所有在回收站的文章
        json.put("mappingList",mappingBeenList);
        json.put("contentDraftList",contentDraftList);//所有草稿文章
        json.put("draftCount",draftCount);
        response.getWriter().print(json.toJSONString());
    }
    @RequestMapping("/moveToBin")
    public void moveToBin(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String content_id = request.getParameter("content_id");
        String tip=request.getParameter("tip");
        String user_id =  ((UserBean)request.getSession().getAttribute("admin")).getUser_id();
        JSONObject json = new JSONObject();
        Map map = new HashMap<>();
        map.put("content_id",content_id);
        map.put("user_id",user_id);
        if("Bin".equals(tip)){
            boolean result = contentService.moveToBin(map);
            if(result){
                json.put("msg","yes");
            }else{
                json.put("msg","no");
            }
        }else if("NoBin".equals(tip)){
            boolean result = contentService.moveToNoBin(map);
            if(result){
                json.put("msg","yes");
            }else{
                json.put("msg","no");
            }
        }
        response.getWriter().print(json.toJSONString());
    }
    @RequestMapping("/delete")
    public void delete(HttpServletRequest request, HttpServletResponse response) throws IOException {
        int content_id = Integer.parseInt(request.getParameter("content_id"));
        JSONObject json = new JSONObject();
        boolean result = contentService.delete(content_id);
        if(result){
            json.put("msg","yes");
        }else{
            json.put("msg","no");
        }
        response.getWriter().print(json.toJSONString());
    }
    @RequestMapping("/getAllType")
    public void getAllType(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<TaxonomyBean> list = contentService.getAllType();
        request.setAttribute("list",list);
        request.getRequestDispatcher("/WEB-INF/admin/content/publishContent.jsp").forward(request,response);
    }
    @RequestMapping("/test")
    public void test(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String data = request.getParameter("data");
        response.getWriter().print("1");
    }
    @RequestMapping("/getContentDetail")
    public void getContentDetail(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String content_id = request.getParameter("content_id");
        ContentBean content = contentService.getContentDetail(content_id);
        List<TaxonomyBean> list = contentService.getAllType();
        List<TaxonomyBean> typeList = contentService.getTypeById(content_id);
        List<MappingBean> mappingBeenList = contentService.getmapping();
        String tip = request.getParameter("tip");
        request.setAttribute("tip",tip);
        request.setAttribute("content",content);
        request.setAttribute("mappingList",mappingBeenList);
        //System.out.println(content.getContent_text());
        request.setAttribute("list",list);
       // System.out.println(list.size());
        request.setAttribute("typeList",typeList);
        request.getRequestDispatcher("/WEB-INF/admin/content/editContent.jsp").forward(request,response);
    }
    @RequestMapping("/search")
    public void getSearchList(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        String content_title = request.getParameter("content_title");
        String tip = request.getParameter("tip");
        JSONObject json = new JSONObject();
        List<ContentBean> searchList = contentService.getSearchList(content_title,tip);
        List<MappingBean> mappingBeenList = contentService.getmapping();
        json.put("searchList",searchList);
        System.out.println("searchList.size()"+searchList);
       // System.out.println("searchList.size()"+searchList.size());
        json.put("mappingList",mappingBeenList);
        response.getWriter().print(json.toJSONString());
    }
    @RequestMapping("/upload")
    public void upload(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/html");
        response.setCharacterEncoding("UTF-8");
        CommonsMultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        String filename="";
        String path="";
        if(resolver.isMultipart(request)){
            MultipartHttpServletRequest multiRequest =  (MultipartHttpServletRequest)request;
            MultipartFile multiFile = multiRequest.getFile("uploadFileInput");
            if(!multiFile.isEmpty()) {
                filename = multiFile.getOriginalFilename();
                //log.info("111"+filename);
                filename = new Date().getTime()+filename.substring(filename.lastIndexOf("."));
                //log.info("222"+filename);
                 path = request.getServletContext().getRealPath("/") + "/static/uploadfiles/";
                File fileDir = new File(path);
                if(!fileDir.exists()){
                    fileDir.mkdirs();
                }
                File file = new File(path,filename);
                if(!file.exists()){
                    file.createNewFile();
                }
                multiFile.transferTo(file);

               // adminUser.setUser_avatar("/static/file/avatar/" + filename);
            }
            String path1 = "/static/uploadfiles/"+filename;
            log.info(path1);
                response.setStatus(2000);
                JSONObject json = new JSONObject();
                json.put("src",path1);
//                String retxt ="{src:'"+path1+"/"+filename+"',status:success}";
                response.getWriter().print(json.toJSONString());
            }


    }

}
